package com.xhu.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhu.common.ResponseInfo;
import com.xhu.common.request.GetByMonthReq;
import com.xhu.common.request.Page;
import com.xhu.common.request.PredictRequest;
import com.xhu.constant.SessionConstant;
import com.xhu.exceptions.SalePredictionException;
import com.xhu.pojo.SalePrediction;
import com.xhu.service.SalePredictionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.xhu.constant.ResultConstant.SUCCESS;


/**
 * 销售预测controller
 */
@RestController
@RequestMapping("/salePre")
public class SalePredictionController extends MyBaseController {

    private static final String PATH = "D:\\crmsystem";

    @Autowired
    SalePredictionService service;

    @PostMapping("/all")
    public String listAllPredictions(@RequestBody Page page) {
        ResponseInfo<Map<String, Object>> response = new ResponseInfo<>();

        IPage<SalePrediction> result = service.getAllPrediction(page.getCurrent(), page.getSize());

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("pageCount", result.getPages());
        resMap.put("content", result.getRecords());

        response.setStatus(SUCCESS);
        response.setData(resMap);

        return JSON.toJSONString(response);
    }

    @PostMapping("/uploadFile")
    public String uploadXlsx(@RequestParam MultipartFile file, HttpServletRequest request) {


        if (file.isEmpty()) {
            throw new SalePredictionException("文件为空");
        }
        File uploadrDir = new File(PATH);
        if (!uploadrDir.exists()) {
            uploadrDir.mkdir();
        }

        String originFileName = file.getOriginalFilename();
        //判空
        if (!StringUtils.hasText(originFileName)) {
            throw new SalePredictionException("文件名字为空");
        }
        //获取后缀
        String suffixName = originFileName.substring(originFileName.lastIndexOf("."));
        //随机生成名字
        String fileanme = UUID.randomUUID() + suffixName;
        File localFile = new File(PATH, fileanme);
        //移动文件到本地目录
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new SalePredictionException("上传失败");
        }

        ResponseInfo<Void> res = new ResponseInfo<Void>()
                .setMsg("上传成功")
                .setStatus(SUCCESS);

        request.getSession().setAttribute(SessionConstant.PREDICTION_FILEPATH, fileanme);

        return JSON.toJSONString(res);

    }

    @PostMapping("/predict")
    public String predict(@RequestBody PredictRequest predictEntity, HttpServletRequest request) {
        String filename = ((String) request.getSession().getAttribute(SessionConstant.PREDICTION_FILEPATH));
        //判空
        if (!StringUtils.hasText(filename)) {
            throw new SalePredictionException("尚未上传文件");
        }
        service.predict(predictEntity, new File(filename));
        //最后清除session中的临时文件
        request.getSession().removeAttribute(SessionConstant.PREDICTION_FILEPATH);
        ResponseInfo<Void> res = new ResponseInfo<Void>()
                .setMsg("预测成功")
                .setStatus(SUCCESS);
        return JSON.toJSONString(res);
    }

    @PostMapping("/getByMonth")
    public String getByMonth(@RequestBody GetByMonthReq req) {
        IPage<SalePrediction> result = service.getByDateTime(req.getStringTime()
                , req.getCurrentPage()
                , req.getSize());

        return this.returnPages(result);
    }
}
